package example.字符串.对称补齐;


import java.util.Stack;

/**
 * 给出一个仅包含字符'(',')','{','}','['和']',的字符串，判断给出的字符串是否是合法的括号序列
 * 括号必须以正确的顺序关闭，"()"和"()[]{}"都是合法的括号序列，但"(]"和"([)]"不合法。
 */
// NC52 括号序列
public class Demo1 {

    //[[{}]]    ((( [ )]))
    public static boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                //左边括号都没有，false
                if (stack.isEmpty()) {
                    return false;
                }
                Character pop = stack.pop();
                if (c == ')' && pop == '(') {
                    continue;
                } else if (c == ']' && pop == '[') {
                    continue;
                } else if (c == '}' && pop == '{') {
                    continue;
                }
                return false;
            }
        }
        return stack.isEmpty();
    }

    public static boolean isValid1(String s) {
        Stack<Character> stack1 = new Stack<>();
        Stack<Character> stack2 = new Stack<>();
        Stack<Character> stack3 = new Stack<>();
        char[] chars = s.toCharArray();
        if (chars.length == 1) {
            return false;
        }
        for (char aChar : chars) {
            if (aChar == '(') {
                stack1.push(aChar);
            } else if (aChar == '[') {
                stack2.push(aChar);
            } else if (aChar == '{') {
                stack3.push(aChar);
            } else if (aChar == ')') {
                if (stack1.isEmpty()) {
                    return false;
                } else {
                    stack1.pop();
                }
            } else if (aChar == ']') {
                if (stack2.isEmpty()) {
                    return false;
                } else {
                    stack2.pop();
                }
            } else if (aChar == '}') {
                if (stack3.isEmpty()) {
                    return false;
                } else {
                    stack3.pop();
                }
            }
        }
        return stack1.isEmpty() && stack2.isEmpty() && stack3.isEmpty();
    }

    public static void main(String[] args) {
//        System.out.println(isValid("([)]"));
        System.out.println(isValid(" ((([)]))"));
        System.out.println(isValid("[[()]]"));
    }
}
